package com.diancan;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.List;

import com.SqlLiteDB.MenuDataHelper;
import com.Utils.FileUtils;
import com.Utils.MenuUtils;
import com.model.AllDomain;
import com.model.Category;
import com.model.Desk;
import com.model.Recipe;

import android.R.integer;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class UpdatePage extends Activity {
	TextView titleTextView;
	TextView updaTextView;
	Button yesButton;
	Button noButton;
	AllDomain infos;
	ProgressDialog mpDialog;
	ProgressBar pBar;
	int mCount;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.updatepage);
		titleTextView=(TextView)findViewById(R.id.updatetitle);
		updaTextView=(TextView)findViewById(R.id.updatetxt);
		pBar=(ProgressBar)findViewById(R.id.pb);
		yesButton=(Button)findViewById(R.id.btn_updatenow);
		noButton=(Button)findViewById(R.id.btn_updatewait);
		yesButton.setOnClickListener(new YesBtnClick());
		noButton.setOnClickListener(new NoBtnClick());
		pBar.setVisibility(View.INVISIBLE);
		Intent intent=getIntent();
		infos=(AllDomain)intent.getSerializableExtra("infos");
		titleTextView.setText("有数据更新");
	}
	//下载数据
    public void DownLoadData()
    {
//    	infos=MenuUtils.DownloadMenusData();	
//		if(infos==null)
//		{
//			Toast toast = Toast.makeText(UpdatePage.this, "更新失败！", Toast.LENGTH_SHORT); 
//          	toast.show(); 
//			return;
//		}
		java.util.Date date=infos.getDate();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		String strdate=simpleDateFormat.format(date);
		MenuDataHelper.OpenDatabase();
		MenuDataHelper.InsertUpdateTime(strdate);
		mCount=0;
		if(infos.getAddRcipes()!=null)
		{
			mCount+=infos.getAddRcipes().size();
		}
		if(infos.getUpdateRecipes()!=null)
		{
			mCount+=infos.getUpdateRecipes().size();
		}
		if(infos.getAddCategories()!=null)
		{
			mCount+=infos.getAddCategories().size();
		}
		if(infos.getUpdateCategories()!=null)
		{
			mCount+=infos.getUpdateCategories().size();
		}
		pBar.setVisibility(View.VISIBLE);
		pBar.setMax(mCount);
		DownloadTask dTask = new DownloadTask();  
        dTask.execute(50);
    }
    public void ToCategoryList()
    {
    	MenuGroup parent = (MenuGroup) getParent();
	    final LinearLayout contain = (LinearLayout) parent.findViewById(R.id.group_Layout);
		contain.removeAllViews();
		Intent in = new Intent(getParent(), CategoryList.class);
		LocalActivityManager manager = parent.getLocalActivityManager();
//		String currentId = manager.getCurrentId();
		Window window = manager.startActivity("CategoryList", in);		
		View view=window.getDecorView();		
		contain.addView(view);
		LayoutParams params=(LayoutParams) view.getLayoutParams();
        params.width=LayoutParams.FILL_PARENT;
        params.height=LayoutParams.FILL_PARENT;
        view.setLayoutParams(params);
    }
    class YesBtnClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			v.setEnabled(false);
			titleTextView.setText("更新中.........");
			DownLoadData();
		}
    	
    }
    class NoBtnClick implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ToCategoryList();
		}
    	
    }
    class DownloadTask extends AsyncTask<Integer, Integer, String>{  
        //后面尖括号内分别是参数（例子里是线程休息时间），进度(publishProgress用到)，返回值 类型  
          
        @Override  
        protected void onPreExecute() {  
            //第一个执行方法  
            super.onPreExecute();  
        }  
          
        @Override  
        protected String doInBackground(Integer... params) {  
            //第二个执行方法,onPreExecute()执行完后执行  
        	
        	try{  
        		int i=1;
                List<Category> categorylist=infos.getAddCategories();
                List<Desk> desklist=infos.getAddDesks();
                List<Integer> dCategories=infos.getDeleteCategories();
                List<Integer> dDesks=infos.getDeleteDesks();
                List<Category> uCategories=infos.getUpdateCategories();
                List<Desk> uDesks=infos.getUpdateDesks();
                if (dCategories!=null) {
					for (int id : dCategories) {
						MenuUtils.DeleteCategoryObj(id);
					}
				}
				if (dDesks!=null) {
					for (int id : dDesks) {
						MenuDataHelper.deletefromdesk(id + "");
					}
				}
				if (uCategories!=null) {
					for (Category category : uCategories) {
						MenuUtils.UpdateCategoryObj(category);
						pBar.setProgress(i);
						publishProgress(i);
						i++;
					}
				}
				if (uDesks!=null) {
					for (Desk desk : uDesks) {
						MenuDataHelper.updatecateDesk(desk);
					}
				}
				if (categorylist!=null) {
					for (Category category : categorylist) {
						MenuUtils.InsertCategoryObj(category);
						pBar.setProgress(i);
						publishProgress(i);
						i++;
					}
				}
				if (desklist!=null) {
					for (Desk desk : desklist) {
						MenuDataHelper.InsertDesk(desk);
					}
				}
				List<Recipe> recipelist=infos.getAddRcipes();
                List<Integer> drecipes=infos.getDeleteRecipes();
                List<Recipe> uRecipes=infos.getUpdateRecipes();
                
                if (drecipes!=null) {
					for (int id : drecipes) {
						MenuUtils.DeleteMenuObj(id);
					}
				}
				if (uRecipes!=null) {
					for (Recipe recipe : uRecipes) {
						MenuUtils.UpdateMenuObj(recipe);
						pBar.setProgress(i);
						publishProgress(i);
						i++;
					}
				}
				if (recipelist!=null) {
					for (Recipe recipe : recipelist) {
						MenuUtils.SaveMenuObj(recipe);
						pBar.setProgress(i);
						publishProgress(i);
						i++;
					}
				}
			pBar.setProgress(mCount);
               publishProgress(mCount);
            }catch(Exception ex){  
            	ex.printStackTrace();
            	return "更新失败"; 
            }  
        	
//            for(int i=0;i<=100;i++){  
//                pBar.setProgress(i);  
////                publishProgress(i);
//                try {  
//                    Thread.sleep(params[0]);  
//                } catch (InterruptedException e) {  
//                    e.printStackTrace();  
//                }  
//            }  
            return "更新成功";  
        }  
  
        @Override  
        protected void onProgressUpdate(Integer... progress) {  
            //这个函数在doInBackground调用publishProgress时触发，虽然调用时只有一个参数  
            //但是这里取到的是一个数组,所以要用progesss[0]来取值  
            //第n个参数就用progress[n]来取值  
//            tv.setText(progress[0]+"%");  
        	int i=(progress[0]*100)/mCount;
        	updaTextView.setText(i+"%");
            super.onProgressUpdate(progress);  
        }  
  
        @Override  
        protected void onPostExecute(String result) {  
            //doInBackground返回时触发，换句话说，就是doInBackground执行完后触发  
            //这里的result就是上面doInBackground执行后的返回值，所以这里是"执行完毕"  
//            setTitle(result);  
            super.onPostExecute(result); 
            MenuDataHelper.CloseDatabase();
            pBar.setVisibility(View.INVISIBLE);
        	titleTextView.setText(result);
        	if(result.equals("更新成功"))
        		ToCategoryList();
        	else {
				yesButton.setEnabled(true);
			}
        }  
          
    }  
}
